package cn.jly.servlet3;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

/**
 * @author lanyangji
 * @description helloServlet
 * @date 2020/11/14 上午 11:42
 */
@WebServlet(name = "helloServlet", urlPatterns = "/helloServlet")
public class HelloServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println(Thread.currentThread() + " start .. ");

        // 非异步请求，会一直阻塞等待返回
        try {
            sayHello();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        final String name = req.getParameter("name");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        final PrintWriter writer = resp.getWriter();
        writer.write("hello, " + name);

        // 打印日志在控制台
        System.out.printf("---> name = %s%n", new String(name.getBytes(StandardCharsets.UTF_8)));

        System.out.println(Thread.currentThread() + " end .. ");

    }

    private void sayHello() throws InterruptedException {
        System.out.println(Thread.currentThread() + " processing ..");
        Thread.sleep(3000);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
